/*
 * Copyright (c) 2017 22420103@QQ.COM 版权所有
 */
package com.lehe.controller;

import com.lehe.common.Contants;
import com.lehe.common.exceptions.LHException;
import com.lehe.common.utils.StringUtil;
import com.lehe.entry.UserInfoDto;
import com.lehe.entry.UserSessionDto;
import com.lehe.service.impl.UserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Arrays;
import java.util.List;

/**
 * 微信授权后回调跳转的页面，也就是微信的入口URL
 *
 * @author 王丹
 * @since 2017-02-25
 */
@Controller
@RequestMapping("index")
public class IndexController extends Basecontroller {

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 正式环境入口-用户登录
     * @param code
     * @return http://admin.lehexinxi.com/forward.php
     * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa79e12d33f38c86e&redirect_uri=http://mp.qpqpgame.com/index&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect
     * @throws LHException
     */
    @RequestMapping
    public String index(@RequestParam(value="code") String code) throws LHException {
        if(null == getUserSession()){
            String wxUnionId = userInfoService.invokeWxForUnionId(code);
            UserInfoDto userInfoDto = userInfoService.queryUserInfo(null, wxUnionId);
            if(null == userInfoDto){
                throw new LHException("您的微信号未注册");
            }
            if(null == userInfoDto.getAgentId() || userInfoDto.getAgentId()<=0 || !StringUtil.isAgent(userInfoDto.getUserLevel())){
                throw new LHException("您的权限不是代理用户");
            }
            UserSessionDto sessionDto = new UserSessionDto();
            BeanUtils.copyProperties(userInfoDto, sessionDto);
            session.setAttribute(Contants.SESSION_USER_KEY, sessionDto);
        }
        return "redirect:/main";
    }

    /**
     * 测试环境入口-用户登录
     * @return
     * @throws LHException
     */
    @RequestMapping("test")
    public String test() throws LHException {
        UserSessionDto sessionDto = new UserSessionDto();
        //sessionDto.setUserId(100540L);
        //sessionDto.setAgentId(998998L);
        sessionDto.setUserId(100630L);
        sessionDto.setAgentId(111888L);
        session.setAttribute(Contants.SESSION_USER_KEY, sessionDto);
        return "redirect:/main";
    }
    
    @RequestMapping("down")
    public String down() throws LHException {
    	return "down/down";
    }
}
